<?php
class Controller_Admin_Quality extends Controller_Template
{
    public function __construct($request,$response)
    {
        parent::__construct($request,$response);
        $this->template	= ('smarty:statistics/quality/index');
    }
    
    public function action_online()
    {
        if (!$this->permission_validation('online'))
        {
            throw new Exception_Access("没有权限");
        }
        $this->show_list('online');
    }
    
    public function action_offline()
    {
        if (!$this->permission_validation('offline'))
        {
            throw new Exception_Access("没有权限");
        }
        $this->show_list('offline');
    }
    
    public function action_set_ignore()
    {
        $id = intval(Arr::get($this->request->query(), 'id', 0));
        $info = Quality::get_info($id);
        if (empty($info))
        {
            return $this->_error('错误的参数');
        }
        $last_day = Quality::last_day();
        if ($info['day'] != $last_day)
        {
            return $this->_error("请在[{$last_day}]的数据列表中设置");
        }
        if ($info['status'] != 'unqualified')
        {
            return $this->_error('只有不合格状态可以设置忽略');
        }
        if ($info['ignore'] == 1)
        {
            return $this->_error('已经设置了忽略');
        }
        if (!$this->permission_validation($info['chntype']))
        {
            return $this->_error('没有权限');
        }
        if (Quality::set_ignore($id))
        {
            $this->_success('设置为忽略成功');
        }
        $this->_error('设置失败，请稍后再试');
    }
    
    private function show_list($chntype = 'online')
    {
        $query = $this->build_query($chntype);
        $sub_type = Kohana::config('channel.type.sub_type');
        if (!empty($query['sub_type']))
        {
            if (!isset($sub_type[$query['sub_type']]))
                throw new Exception('无效的子渠道类型');
            $ids = Promotion_Channel::chnids_by_subtype($query['sub_type']);
            $query['channel_id'] = $ids ? $ids : 0;
        }
        $result = Quality::search($query);
        $result = $this->build_data($result);
        $status_arr = array('qualified'=>'合格', 'unqualified'=>'不合格', 'observe'=>'观察中');
        $chntype_arr = array('online'=>'线上', 'offline'=>'线下', 'unknow'=>'未知');
        $allow_compare = array(
            'retentionRate' => '次日留存', 
            'actusers'      => '活跃用户', 
            'newusers'      => '日新增数', 
            'searchs'       => '日搜索数', 
            'downloads'     => '日下载数', 
            'lifetime'      => '日均时长', 
            'avgDownload'   => '下载比例', 
            'avgSearch'     => '搜索比例', 
            'ratio'         => '建议系数'
        );
        $this->template->set('data', $result);
        $this->template->set('sub_type', $sub_type);
        $this->template->set('status_arr', $status_arr);
        $this->template->set('allow_compare', $allow_compare);
        $this->template->set('query', $query);
        $this->template->set('data_count', count($result));
        $this->template->set('sum_data', $this->sum_data($result));
        $this->template->set('chntype', $chntype_arr[$chntype]);
        $this->template->set('config', json_encode(Quality::get_config($chntype)));
        $this->template->set('last_day', Quality::last_day());
        $this->template->set_filename('smarty:statistics/quality/index');
    }
    
    private function build_query($chntype = 'online')
    {
        $query = $this->request->query();
        //排序
        if (empty($query['order_by']) || strpos($query['order_by'], '|') === false)
        {
            $query['order_by'] = array('newusers' => 'desc');
        }
        else 
        {
            $tmp = explode('|', $query['order_by']);
            $query['order_by'] = array($tmp[0] => !empty($tmp[1]) && $tmp[1] == 'asc' ? 'asc' : 'desc');
        }
        //筛选
        if (!empty($query['search_key']) && !empty($query['search_value']))
        {
            $query[$query['search_key']] = $query['search_value'];
        }
        $query['chntype'] = $chntype;
        return $query;
    }
    
    private function build_data($data)
    {
        foreach ($data as $k => $v)
        {
            $info = Promotion_Channel::cpa_channel_info_by_chnid($v['channel_id']);
            $type = Promotion_Channel::channel_type($info['unique_key']);
            $data[$k]['umeng_id']       = isset($info['umeng_id']) ? $info['umeng_id'] : '-';
            $data[$k]['unique_key']     = isset($info['unique_key']) ? $info['unique_key'] : '-';
            $data[$k]['name']           = isset($info['name']) ? $info['name'] : '-';
            $data[$k]['merchant_id']    = isset($info['merchant_id']) ? $info['merchant_id'] : '-';
            $data[$k]['create_time']    = isset($info['create_time']) ? date('Y-m-d', $info['create_time']) : '-';
            $data[$k]['manager_id']     = isset($info['manager_id']) ? $info['manager_id'] : '-';
            $data[$k]['manager_name']   = isset($info['manager_name']) ? $info['manager_name'] : '-';
            $data[$k]['activity_id']    = isset($info['activity_id']) ? $info['activity_id'] : '-';
            $data[$k]['sub_type']       = Arr::get($type, 'sub_type', 0);
            if (!$v['observe_days'])
            {
                $data[$k]['observe_days'] = '-';
            }
        }
        return $data;
    }
    
    private function sum_data($data)
    {
        $sum = array('actusers'=>0, 'newusers'=>0, 'searchs'=>0, 'downloads'=>0);
        foreach ($data as $v)
        {
            foreach ($sum as $key => $val)
            {
                $sum[$key] += $v[$key];
            }
        }
        return $sum;
    }
    
    /**
     * 查看权限
     *
     * @param string $chntype
     * @return boolean
     */
    private function permission_validation($chntype)
    {
        $passport = User::passport();
        if (in_array($passport, array('luyankai@appchina.com', 'yangxiaoliang2@appchina.com', 'yuancong@appchina.com'))) return true;
        if ($chntype == 'online' && $passport == 'zhaodongdong@appchina.com') return true;
        if ($chntype == 'offline' && $passport == 'jinmaomao@appchina.com') return true;
        return false;
    }
    
    private function _error($msg)
    {
        echo json_encode(array('status'=>0, 'msg'=>$msg));
        exit;
    }
    
    private function _success($msg)
    {
        echo json_encode(array('status'=>1, 'msg'=>$msg));
        exit;
    }
}
